﻿#===============================================================================
# Набор классов для вытаскивания страниц с vkontakte.ru
#===============================================================================
import urllib, urllib2, cookielib
import os, re, time, traceback

from vapi.tools.parser import VkontakteProfileParser, VkontakteNewsParser
#from tools.parser import VkontakteProfileParser, VkontakteNewsParser

import ClientForm

class BaseLeecher(object):    
    # Некий личер. Sleep time - промежуток между запросами, дабы не забанили
    login = ""
    password = ""
    sleep_time = 2
    
    def __init__(self, login, password):
        
        self.login = login
        self.password = password
        self.cj = cookielib.CookieJar()
         
    def get_opener(self):
        newopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
        newopener.addheaders = [('User-agent', 'Opera/9.50 (Windows NT 5.1; U; en)')]
        return newopener
    
    def get_opera_full_opener(self, host, referer):
        newopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
        newopener.addheaders = [('User-agent', 'Opera/9.26 (Windows NT 5.1; U; en)')]
        newopener.addheaders = [('Host', host)]
        newopener.addheaders = [('Accept', 'text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1')]
        newopener.addheaders = [('Accept-Language', 'ru-RU,ru;q=0.9,en;q=0.8')]
        newopener.addheaders = [('Accept-Encoding', 'deflate, gzip, x-gzip, identity, *;q=0')]
        newopener.addheaders = [('Referer', referer)]
        newopener.addheaders = [('Cookie2', '$Version=1')]
        newopener.addheaders = [('Accept-Charset', 'iso-8859-1, utf-8, utf-16, *;q=0.1')]
        newopener.addheaders = [('Referer', 'http://mail.yandex.ru/')]
        return newopener
    
    def get_mozilla_opener(self):
        newopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
        newopener.addheaders = [('User-agent', 'Mozilla/5.0')]
        return newopener

class VkontakteLeecher(BaseLeecher):
    # Личер заточенный под vkontakte.ru
    # Путь к логам пока такой
    email = ""
    password = ""
    log_file = "c:/error.vapi"

    def __init__(self, email, password):
        self.email = email
        self.password = password
        self.cj = cookielib.CookieJar()

    def login(self):
        # Логинимся на сайт. Если успешно - тошним страничку профайла, если нет пишем в логи ошибку.
        try:
            params = urllib.urlencode({'email': self.email, 'pass': self.password})
            fpage = self.get_opener().open("http://vkontakte.ru/login.php?%s" %params)
            time.sleep(self.sleep_time)
            return fpage
        except Exception, inst:
            if inst.args[0]=='Wrong password':
                out=open(self.log_file,"a")
                traceback.print_exc(inst,out)
                out.close()
                print "Login failed, email.\n"
            else:
                out=open(self.log_file,"a")
                traceback.print_exc(inst,out)
                out.close()                            
        except:
            out=open(self.log_file,"a")
            traceback.print_exc(None,out)
            out.close()        
            print "Some Error"
    
    def get_news(self):
        # Тащим новости. Смотрим, чтобы все галочки в форме с фильтрами стояли
        try:
            forms = ClientForm.ParseResponse(self.get_opener().open("http://vkontakte.ru/news.php"), backwards_compat=False)
            form = forms[1]
            for i in range(0,11):
                form.find_control("field%i" %i).items[0].selected = True
            request = form.click()
            fpage = self.get_opener().open(request)
            return fpage
        except Exception, inst:
            if inst.args[0]=='Wrong password':
                out=open(self.log_file,"a")
                traceback.print_exc(inst,out)
                out.close()
                print "Login failed, email.\n"
            else:
                out=open(self.log_file,"a")
                traceback.print_exc(inst,out)
                out.close()                            
        except:
            out=open(self.log_file,"a")
            traceback.print_exc(None,out)
            out.close()        
            print "Some Error"
    
    def get_mail(self):
        pass
    
    def get_friends(self):
        pass
    
    def get_profile(self, idnum):
        try:
            fpage = self.get_opener().open("http://vkontakte.ru/profile.php?id=%s" %idnum)
            time.sleep(self.sleep_time)
            return fpage
        except Exception, inst:
            if inst.args[0]=='Wrong password':
                out=open(self.log_file,"a")
                traceback.print_exc(inst,out)
                out.close()
                print "Login failed, email.\n"
            else:
                out=open(self.log_file,"a")
                traceback.print_exc(inst,out)
                out.close()                            
        except:
            out=open(self.log_file,"a")
            traceback.print_exc(None,out)
            out.close()        
            print "Some Error"
    
    
    def get_avatar(self, profile_page):
        pass
    
    def get_photos_with_me(self, profile_page):
        pass
    
    def get_events(self):
        pass

    def get_photos(self):
        pass
    
    def get_video(self):
        pass
    
    def get_audio(self):
        pass
    
    def get_notes(self):
        pass
    
    def get_groups(self):
        pass
    
    def get_group_profile(self):
        pass
    
    def get_fave(self):
        pass
    
    def get_settings(self):
        pass
    
    def get_matches(self):
        pass
    
    def get_apps(self):
        pass
    
    def get_questions(self):
        pass
    
    def get_opinions(self):
        pass
    
    def get_attention(self):
        pass
    

